'''
Created on 2012-9-5

@author: Administrator
'''
from common.util import validate_login_session
from common.util import do_render
from common.util import render_template
from model.models import User
from model.models import Comment
from model.models import Blog
from common.util import Logger
from model.models import get_tuple_by_key
from model import models
from common.sessions import Session
from controller import pervlets

from google.appengine.ext import webapp
from google.appengine.ext import db


logger_ = Logger()
default_user_ = db.Query( User ).filter( 'username =', models._QUINTUS_USERNAME ).filter( 'password =', models._QUINTUS_PASSWORD ).get()

def get_user_by_user_name( handler ):
    return User( username = handler.session['username'] )

class RequestCommentHandler( webapp.RequestHandler ):
    def get( self ):
        self.post()
        
    def post( self ):
        if not validate_login_session( self ):
            # invalid user TODO
            pass
        
        user = get_user_by_user_name( self )
        comment = Comment( user = user )
        query = db.Query( comment )
        result = query.fetch()
        #TODO
        
class CommentHandler( webapp.RequestHandler ):
    _TEXT = 'text'
    def get( self ):
        self.post()
    
    def post( self ):
        # if not validate_login_session( self ):
            # invalid user TODO
        #    pass
        
        # user = get_user_by_user_name( self )
        # comment = Comment( user = user, text = self.request.get( CommentHandler._TEXT ) )
        # comment.put()
        render_template( self.response.out, 'templates/comment.html' )

class IndexHandler( webapp.RequestHandler ):
    INDEX_ = 'templates/index.html'
    
    def get( self ):
        self.post()
    
    def post( self ):
        whats_new = models.get_last_news( default_user_ )
        
        hint = {}
        #now, only support new blogs
        if isinstance( whats_new, models.Blog ) :
            hint = {'title':whats_new.title, 'time':whats_new.time, 'picture':whats_new.picture, 'text':whats_new.text, 'blog':'blog', 'blogpicture':whats_new.picture}
        elif isinstance( whats_new, models.Life ):
            hint = {'life':'life', 'key':str( whats_new.key() ), 'time':whats_new.time, 'comment':whats_new.comment}#comment TODO
        #add lastest comments snapshot
        lasted_two_blog_comments = models.get_tuple_by_key( models.BlogComment, 2, 0, orderby = 'time' )
        last_comments_list_ = []
        for comment in lasted_two_blog_comments:
            guest_name = models.get_by_pk( models.User, comment.user.key() ).nickname
            guest_website = models.get_by_pk( models.User, comment.user.key() ).website
            blog_name = models.get_by_pk( models.Blog, comment.blog.key() ).title
            blog_catelog = models.get_by_pk( models.Blog, comment.blog.key() ).catelog
            blog_time = comment.time
            last_comments_list_.append( {'name':guest_name, 'blog':blog_name, 'time':blog_time, 'website':guest_website, 'catelog':blog_catelog} )
            
        #add blog archivements snapshot
        last_two_blog_archivements = models.get_tuple_by_key( models.Blog, 2, 0, orderby = 'time' )
        last_blogs = []
        for blog in last_two_blog_archivements:
            blog_time_ = blog.time
            blog_title = blog.title
            blog_catelog = blog.catelog
            last_blogs.append( {'title':blog_title, 'catelog':blog_catelog, 'time':blog_time_} )
        
        hint['lastcomments'] = last_comments_list_
        hint['lastblogs'] = last_blogs
        
        do_render( self, IndexHandler.INDEX_, hint )

class DefaultHandler( webapp.RequestHandler ):
    def get( self ):
        self.post()
    
    def post( self ):
        logger_.info( "request path : " + self.request.path + "; default handler --> index.html" )
        self.redirect( "/index.html", True ) 
        #TODO

class LifeHandler( webapp.RequestHandler ):
    def get( self ):
        self.post()
    
    def post( self ):
        lifes = models.Life.all().filter( 'user', default_user_.key() ).order( 'time' )
        life_list = []
        temp_list = []
        temp_month = temp_year = -1
        latest_update_time = -1
        import copy
        for life in lifes:
            if temp_month == temp_year == -1 or temp_year == life.time.year and temp_month == life.time.month:
                temp_list.append( {'time':life.time, 'key':str( life.key() ), 'comment':life.comment} )
                temp_month = life.time.month
                temp_year = life.time.year
                if latest_update_time == -1:
                    latest_update_time = life.time
            else:
                temp_month = life.time.month
                temp_year = life.time.year
                life_list.append( {'year_month':life.time, 'life_in_one_month_of_year':copy.copy( temp_list )} )
                temp_list = []
                temp_list.append( {'time':life.time, 'key':str( life.key ), 'comment':life.comment} )
        try:        
            life_list.append( {'year_month':life.time, 'life_in_one_month_of_year':copy.copy( temp_list )} ) 
            do_render( self, 'templates/life.html', {'lifes':life_list, 'latest_update_time':latest_update_time} )   
        except UnboundLocalError, e:
            logger_.error( '***********ERROR**********ERROR**********ERROR**********', str( e ) )
            do_render( self, 'templates/life.html' )
        

class AboutHandler( webapp.RequestHandler ):
    def get( self ):
        self.post()
    
    def post( self ):
        do_render( self, 'templates/about.html' , {'default_user':str( default_user_.key() )} )
        
class ContactHandler( webapp.RequestHandler ):
    def get( self ):
        self.post()
    
    def post( self ):
        do_render( self, 'templates/contact.html' )
        
class BlogHandler( webapp.RequestHandler ):
    def get( self ):
        self.post()
        
    def post( self ):
        if default_user_:
            list_ = []
            results = get_tuple_by_key( Blog, limit = 20, offset = 0, user = default_user_.key() , orderby = 'time' )
            blog_archive = models.get_all_blog_list_bundle_by_time()
            for result in results:
                #get comments for current blog
                results_comments = get_tuple_by_key( models.BlogComment, 20, 0, blog = result.key() )
                
                #construct blog content
                dict_ = {'picture':result.picture , 'username':result.user.nickname, 'catelog':result.catelog, 'title':result.title, 'text':result.text, 'time': result.time, 'comments':results_comments}
                #result.user, result.catelog, result.title, result.text, result.time
                list_.append( dict_ )
            #list_.append( {'user':'quintus', 'text':'hello this is first blog', 'title':'Hello world!', 'picture':'static/image/1231.jpg'} )
            do_render( self, 'templates/blog.html', {'results':list_, 'blog_archives':blog_archive} )
            return 
        else:
            #TODO other login user
            return
        do_render( self, 'templates/blog.html' )

class LoginPageHandler( webapp.RequestHandler ):
    def get( self ):
        self.post()
        
    def post( self ):
        do_render( self, 'templates/login.html' )
        
class AdminHandler( webapp.RequestHandler ):
    def get( self ):
        self.post()
        
    def post( self ):
        self.session = Session()
        username = ""
        password = ""
        
        try:
            self.session['username']
            self.session['key']
        except KeyError:
            username = self.request.get( 'username' )
            password = self.request.get( 'password' )
            if  username == "" or password == "":
                render_template( self.response.out, "templates/login.html", {"error":"Please login!"} )
                logger_.error( "User haven't login!" )
                return
            else:
                pass
                result = get_tuple_by_key( User, limit = 2, offset = 0, username = username, password = password )
                
                if  len( result ) > 1:
                    logger_.error( "User duplicated in datastore!", "username : " + username + ", password : " + password + ", result amount : " + str( len( result ) ) )
                    render_template( self.response.out, "templates/login.html", {"error":"User duplicated error in server!"} )
                    return
                elif len( result ) == 0:
                    logger_.info( "User doesn't exist in datastore!", "username : " + username + ", password : " + password )
                    render_template( self.response.out, "templates/login.html", {"error":"User name or password error!"} )
                    return
                
                #create user session
                self.session['username'] = result[0].username
                self.session['nickname'] = result[0].nickname
                self.session['password'] = result[0].password
                self.session['key'] = result[0].key()
        
        #query = db.Query( User )
        #query.filter( 'username =', username ).filter( 'password =', password )
        #result = query.fetch( 2 )
        
        user_context = get_user_context_dict( self.session ) #haven't use
        user_context['user_key'] = str( default_user_.key() )
          
        #render_template( self.response.out, "templates/admin.html", {'blogs':[{'user':'user1', 'title':'title1'}, {'user':'user2', 'title':'title2'}]} )
        render_template( self.response.out, "templates/admin.html", user_context )
        return 
        
        #logger_.info( "User name : " + username + ", password : " + password )
        #render_template( self.response.out, "templates/admin.html" )


class TestReqHandler( webapp.RequestHandler ):
    def get( self ):
        self.post()
    
    def post( self ):
        logger_.info( "========================================THIS IS TEST==================================" )
        logger_.info( "========================================THIS IS TEST==================================" )
        logger_.info( "========================================THIS IS TEST==================================" )
        logger_.info( "========================================THIS IS TEST==================================" )
        logger_.info( "========================================THIS IS TEST==================================" )
        self.response.out.write( "hello this is test!!!!!!" )

def get_user_context_dict( session ):
    '''
    query all user info e.g blogs etc. from DB by user model key which stored in session.
    this function designed as lnx-clouldstore did, but i don't think it's a good design 
    since it will makes session as too much redundancy when those contents are too many.
    '''
    import copy
    dict_ = {}
    list_ = []
   
    #blogs
    blogs = get_tuple_by_key( Blog, limit = 30, offset = 0, user = session['key'] )
    for blog in blogs:
        list_.append( {'key':blog.key(), 'user':blog.user.username, 'title':blog.title, 'catelog':blog.catelog, 'text':blog.text, 'picture':blog.picture, 'time':blog.time} )
    dict_['blogs'] = copy.copy( list_ )
    list_ = []
    
    #contact
    contacts = models.ContactRequest.all().order( '-time' )
    for contact in contacts:
        list_.append( {'name':contact.name, 'email':contact.email, 'mircroblog':contact.mircroblog, 'time':contact.time, 'comments':contact.comments} )
            #lifes = get_tuplete_by_key()
            #contacts = get_tuplete_by_key()
            #comments = get_tuplete_by_key()
            #about = get_tuplete_by_key()
    dict_['contacts'] = copy.copy( list_ )
    list_ = []      
    #TODO LIFE, ABOUT... make they as user context
    
    #life
    lifes = models.Life.all().order( '-time' )
    for life in lifes:
        list_.append( {'time':life.time, 'key':str( life.key() ), 'comment':life.comment} )
    dict_['lifes'] = copy.copy( list_ )
    list_ = []
    
    return dict_
        
